<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
      <template slot="menuLeft">
        <el-button type="primary" size="small" icon="el-icon-plus" @click="handleAddBtn()" v-if="permission.meterialPreparation_add">新 建 </el-button>
        <el-button type="warning" size="small" icon="el-icon-download" @click="handleExport" v-if="permission.meterialPreparation_export">导出 </el-button>
      </template>
      <template slot-scope="{ row }" slot="menu">
        <el-button
          type="text"
          icon="el-icon-view"
          size="small"
          plain
          style="border: 0; background-color: transparent !important"
          v-if="permission.meterialPreparation_view"
          @click.stop="handleView(row)"
          >详情
        </el-button>
      </template>
    </avue-crud>
    <el-dialog append-to-body :close-on-click-modal="false" :title="title" :visible.sync="showDialog" v-if="showDialog" width="60%" top="7vh">
      <avue-crud
        ref="addTableCrud"
        v-model="sheetForm"
        :option="sheetOption"
        :table-loading="roLoading"
        :data="sheetData"
        :permission="permissionList"
        :before-open="beforeOpen"
        :page.sync="roPage"
        @search-change="addSearchChange"
        @search-reset="addSearchReset"
        @current-change="currentRoChange"
        @size-change="sizeRoChange"
        :key="timer"
        @selection-change="selectionDetailChange"
      >
        <template slot-scope="{ row }" slot="generationType">
          <span>{{ row.generationType == 'ERP' ? 'ERP同步' : 'MES新增' }}</span>
        </template>
      </avue-crud>
      <template slot="footer" class="dialog-footer" :style="{ display: isNone }" v-if="title !== '详情'">
        <el-button
          type="primary"
          size="small"
          :icon="title == '新建' ? 'el-icon-circle-plus-outline' : 'el-icon-circle-check'"
          @click="handleMerge()"
          v-preventReClick
          :disabled="selectionDetailList.length == 0"
          >合并</el-button
        >
        <el-button size="small" icon="el-icon-circle-close" @click="reset">取 消</el-button>
      </template>
      <el-dialog append-to-body :close-on-click-modal="false" title="新建" :visible.sync="showDetailDialog" width="60%" top="7vh" class="detail-dialog">
        <div style="margin-bottom: 10px">
          <span>创建方式：</span>
          <el-radio-group v-model="radio" @change="handleRadio(radio)">
            <el-radio :label="1">合并</el-radio>
            <el-radio :label="2">按仓库</el-radio>
            <!-- <el-radio :label="3">自定义</el-radio> -->
          </el-radio-group>
        </div>
        <div v-for="(item, index) in preparationList" :key="index">
          <h2 v-if="radio == 2">{{ '备料单' + (index + 1) }}</h2>
          <avue-crud
            :option="detailOption"
            ref="detailTableCrud"
            @selection-change="selectionDetailChange2"
            :key="timer + index"
            :table-loading="detailLoading"
            :data="preparationList[index].sheetDetails || []"
          >
            <!-- <template slot="footer">

                </template> -->
          </avue-crud>
        </div>
        <div class="dialog-footer">
          <el-button type="primary" size="small" icon="el-icon-circle-plus-outline" @click="handleSubmit()" v-preventReClick>创 建</el-button>
          <el-button size="small" icon="el-icon-circle-close" @click="showDetailDialog = false">取 消</el-button>
        </div>
      </el-dialog>
    </el-dialog>
  </basic-container>
</template>

<script>
import { getList, getPreparationList, getDetail, add, update, remove, getSheetPartList, submitPreparation } from '@/api/warehouse/sheetheader';
import { mapGetters } from 'vuex';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import userTableConfig from '@/components/user-table-config/index.vue';
import userConfig from '@/mixins/userConfig';
export default {
  components: {
    CommonModalTemplate,
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'METERIAL_PERPARATION',
      sourceType: '',
      sheetSubType: '',
      form: {},
      typeObj: {},
      sheetType: '', //采购单类型
      sheetForm: {},
      properties: {},
      radio: 1,
      timer: new Date().getTime(),
      loading: false,
      detailLoading: false,
      roLoading: false,
      isNone: '', //是否显示修改
      title: '',
      receiveRecordNumber: '',
      status: '',
      showDetailDialog: false,
      tableOption: [], //模态框配置
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      roPage: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      roQuery: {},
      search: {},
      rowData: {}, //行数据
      selectionList: [],
      selectionDetailList: [],
      selectionDetailList2: [],
      showDialog: false,
      data: [],
      sheetData: [],
      detailData: [],
      replacePartData: [],
      preparationList: [
        {
          sheetDetails: []
        }
      ],
      option: {
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuPosition: 'right',
        searchMenuSpan: 4,
        searchLabelWidth: '120',
        dialogClickModal: false,
        border: true,
        height: 'calc(100vh - 440px)',
        viewBtn: false,
        addBtn: false,
        selection: true,
        printBtn: false,
        editBtn: false,
        delBtn: false,
        index: false,
        searchSpan: 5,
        columnBtn: false,
        column: [
          {
            label: '备料单号',
            prop: 'sheetNo',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入备料单号',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '生产订单',
            prop: 'productionOrderNoList',
            search: true,
            formatter: (param) => {
              return param.productionOrderNoList ? String(param.productionOrderNoList) : '';
            }
          },
          {
            label: '部门名称',
            prop: 'workshopNameList',
            search: true,
            formatter: (param) => {
              return param.workshopNameList ? String(param.workshopNameList) : '';
            }
          },
          {
            label: '工单号',
            prop: 'workOrderNoList',
            formatter: (param) => {
              return param.workOrderNoList ? String(param.workOrderNoList) : '';
            }
          },
          {
            label: '关联领料单',
            prop: 'sourceNoList',
            rules: [
              {
                required: true,
                message: '请输入关联领料单',
                trigger: 'blur'
              }
            ],
            formatter: (param) => {
              return param.sourceNoList ? String(param.sourceNoList) : '';
            }
          },
          {
            label: '创建时间',
            prop: 'createTime',
            sortable: true,
            rules: [
              {
                required: true,
                message: '请输入创建时间',
                trigger: 'blur'
              }
            ]
          }
        ]
      },
      detailOption: {
        height: '400',
        addBtn: false,
        viewBtn: false,
        selection: false,
        menu: false,
        page: false,
        index: false,
        border: true,
        refreshBtn: false,
        column: [
          {
            label: '物料编码',
            prop: 'partMasterCode'
          },
          {
            label: '物料名称',
            prop: 'partMasterName'
          },
          {
            label: '物料类别',
            prop: 'categoryName'
          },
          {
            label: '领料数量',
            prop: 'quantity',
            type: 'number',
            precision: 10
          },
          {
            label: '推荐仓库',
            prop: 'inventoryName'
          },
          {
            label: '推荐储位',
            prop: 'areaCode'
          }
        ]
      },
      sheetOption: {
        tip: false,
        searchSpan: 4,
        searchMenuSpan: 4,
        dialogClickModal: false,
        height: '400',
        border: true,
        addBtn: false,
        editBtn: false,
        viewBtn: false,
        cancelBtn: false,
        saveBtn: false,
        selection: true,
        menu: false,
        page: true,
        index: false,
        refreshBtn: false,
        expandBtn: false,
        searchShowBtn: false,
        searchShow: true,
        columnBtn: false,
        column: []
      }
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  inject: ['globalStartLoad', 'globalEndLoad'],
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        viewBtn: this.vaildData(this.permission.meterialPreparation_view, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
    roIds() {
      let ids = [];
      this.selectionDetailList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids;
    }
  },
  methods: {
    rowSave(row, done, loading) {
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          console.log(error);
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete(titleCrud) {
      if (titleCrud == 'sheetDel') {
        if (this.selectionList.length === 0) {
          this.$message.warning('请选择至少一条数据');
          return;
        }
        this.$confirm('确定将选择数据删除?', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
            this.$refs.crud.toggleSelection();
          });
      }
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      if (params.productionOrderNoList) {
        params.productionOrderNos = params.productionOrderNoList;
        delete params.productionOrderNoList;
      }
      if (params.workshopNameList) {
        params.workshopNames = params.workshopNameList;
        delete params.workshopNameList;
      }

      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    addSearchReset() {
      this.query = {};
      this.onLoad(this.roPage, {}, 'RO');
    },
    addSearchChange(params, done) {
      this.roQuery = params;
      this.roPage.currentPage = 1;
      this.onLoad(this.roPage, params, 'RO');
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionDetailChange(list) {
      this.selectionDetailList = list;
    },
    selectionDetailChange2(list) {
      this.selectionDetailList2 = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    currentRoChange(currentPage) {
      this.roPage.currentPage = currentPage;
      this.onLoad(this.roPage, {}, 'RO');
    },
    sizeRoChange(pageSize) {
      this.roPage.pageSize = pageSize;
      this.onLoad(this.roPage, {}, 'RO');
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}, sheetType) {
      params.sheetType = sheetType || 'MPL';
      if (sheetType === 'RO') {
        this.roLoading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.roQuery))
          .then((res) => {
            const data = res.data.data;
            this.sheetData = data.records;
            this.roPage.total = data.total;
            this.selectionClear();
          })
          .finally(() => {
            this.roLoading = false;
          });
      } else {
        this.loading = true;
        getPreparationList(page.currentPage, page.pageSize, Object.assign(params, this.query))
          .then((res) => {
            const data = res.data.data;
            this.data = data.records;
            this.page.total = data.total;
            this.selectionClear();
          })
          .finally(() => {
            this.loading = false;
          });
      }
      // sheetType === 'RO' ? (this.roLoading = true) : (this.loading = true);
      // params.sheetType = sheetType || 'MPL';
      // getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
      //   const data = res.data.data;
      //   if (sheetType === 'RO') {
      //     this.sheetData = data.records;
      //     this.roPage.total = data.total;
      //   } else {
      //     this.data = data.records;
      //     this.page.total = data.total;
      //   }
      //   sheetType === 'RO' ? (this.roLoading = false) : (this.loading = false);
      //   this.selectionClear();
      // });
    },
    onDetailLoad(action, ids) {
      this.detailLoading = true;
      getSheetPartList(action, ids).then((res) => {
        const data = res.data.data;
        this.preparationList = data;
        this.detailLoading = false;
        this.selectionClear();
      });
    },
    handleSync() {},
    handleExport() {
      this.$confirm('是否导出备料单数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.globalStartLoad('备料单数据导出中，请稍后...');
        // exportUser(this.search.account, this.search.realName)
        //   .then((res) => {
        //     downloadExcel(res.data, '备料单数据' + new Date().toLocaleString());
        //   })
        //   .finally(() => {
        //     this.globalEndLoad();
        //   });
      });
    },
    reset() {
      this.showDialog = false;
    },
    handleDetailDelete() {
      if (this.selectionDetailList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.sheetData = this._differenceBy(this.sheetData, this.selectionDetailList, 'partMasterCode');
    },
    newKey() {
      this.timer = new Date().getTime();
    },
    handleMerge() {
      this.showDetailDialog = true;
      this.$nextTick(() => {
        this.radio = 1;
      });
      this.preparationList = [
        {
          sheetDetails: []
        }
      ];
      this.onDetailLoad('', this.roIds);
    },
    handleRadio(val) {
      this.preparationList = [
        {
          sheetDetails: []
        }
      ];
      switch (val) {
        case 1:
          this.onDetailLoad('', this.roIds);
          this.newKey();
          this.detailOption.height = 400;
          this.detailOption.selection = false;
          break;
        case 2:
          this.onDetailLoad('INVENTORY', this.roIds);
          this.newKey();
          this.detailOption.selection = false;
          this.detailOption.height = 200;
          break;
        case 3:
          this.onDetailLoad('', this.roIds);
          this.newKey();
          this.detailOption.height = 400;
          this.detailOption.selection = true;
          break;
        default:
          break;
      }
    },

    /*
     * 提交
     */
    handleSubmit() {
      // let sheetDetails = []
      // let params = {}
      // for(let i = 0; i < this.preparationList.length; i++){
      //    params = this.preparationList[0];
      //   let arr = this.preparationList[i].sheetDetails
      //   console.log(this.preparationList, arr, 333333222222222222222)
      //    sheetDetails.push(...arr)
      // }
      // delete params.sheetDetails

      submitPreparation(this.preparationList).then(
        (res) => {
          let data = res.data;
          if (data.code == 200) {
            let sheetNos = [];
            this._forEach(data.data, (item) => {
              sheetNos.push(item.sheetNo);
            });
            this.$message({
              type: 'success',
              message: `备料单${String(sheetNos)}创建成功!`
            });
            this.showDialog = false;
            this.showDetailDialog = false;
            this.refreshChange();
          }
        },
        (error) => {
          window.console.log(error);
        }
      );
    },
    /**
     * 新增模态框
     */
    handleAddBtn() {
      this.title = '新建';
      this.isNone = 'inline';
      this.sheetOption.column = [
        {
          label: '领料单号',
          prop: 'sheetNo',
          search: true,
          searchSpan: 5
        },
        {
          label: '工单号',
          prop: 'sourceNo',
          search: true,
          searchSpan: 5
        },
        {
          label: 'bom版本',
          prop: 'bomVersion'
        },
        {
          label: '产品编码',
          searchSpan: 5,
          prop: 'productNo',
          search: true
        },
        {
          label: '产品名称',
          prop: 'productName',
          searchSpan: 5,
          search: true
        },
        {
          label: '生产日期',
          prop: 'planStartDate'
        },
        {
          label: '单据来源',
          prop: 'generationType'
        },
        {
          label: '最近同步时间',
          prop: 'lastSuccessSyncTime',
          sortable: true
        }
      ];
      this.onLoad(this.roPage, {}, 'RO');
      this.showDialog = true;
    },
    /**
     * 查看模态框
     */
    handleView(row) {
      this.title = '详情';
      this.isNone = 'none';
      this.sheetOption.column = [
        {
          label: '物料编码',
          prop: 'partMasterCode'
        },
        {
          label: '物料名称',
          prop: 'partMasterName'
        },
        {
          label: '物料类别',
          prop: 'categoryName'
        },
        {
          label: '领料数量',
          prop: 'quantity',
          type: 'number',
          precision: 10
        },
        {
          label: '推荐仓库',
          prop: 'inventoryName'
        },
        {
          label: '推荐储位',
          prop: 'areaCode'
        }
        // {
        //     label: '关联领料单',
        //     prop: 'sourceNo'
        // }
      ];
      this.showDialog = true;
      this.getListData(row.id);
    },

    /**
     * 获取单据详情
     */
    getListData(id) {
      this.sheetData = [];
      this.roLoading = true;
      getDetail(id).then((res) => {
        const data = res.data.data;
        this.addTableData(data);
        this.roLoading = false;
      });
    },

    /**
     * 添加单据物料数据 PO
     */
    addTableData(data) {
      this.sourceType = '';
      let tempArr = [];
      for (let i = 0; i < data.length; i++) {
        let item = {
          id: data[i].id,
          sheetLot: this._get(data[i], 'sheetLot', ''),
          lotNo: this._get(data[i], 'lotNo', ''),
          partMasterName: this._get(data[i], 'name', '') || this._get(data[i], 'partMasterName', '') || this._get(data[i], 'partName', ''),
          partMasterCode: this._get(data[i], 'partNo', '') || this._get(data[i], 'partMasterCode', ''),
          partMasterModel: this._get(data[i], 'partModel', '') || this._get(data[i], 'partMasterModel', ''),
          partMasterId: this._get(data[i], 'partMasterId', '') || this._get(data[i], 'partId', ''),
          partType: this._get(data[i], 'partType', ''),
          sheetNo: this._get(data[i], 'sheetNo', ''),
          quantity:
            this._get(data[i], 'quantity', '') ||
            this._get(data[i], 'planQuantity', '') ||
            this._get(data[i], 'receiveQuantity', '') ||
            this._get(data[i], 'sendExamineQuantity', ''),
          sourceNo: this._get(data[i], 'orderNo', '') || this._get(data[i], 'sourceNo', ''),
          completedQuantity: this._get(data[i], 'completedQuantity', '') || 0,
          sourceId: this._get(data[i], 'sourceId', ''),
          inventoryName: this._get(data[i], 'inventoryName', ''),
          areaCode: this._get(data[i], 'areaCode', ''),
          categoryName: this._get(data[i], 'categoryName', '')
        };
        tempArr.push(item);
      }
      this.sheetData = this._orderBy(
        this.sheetData.concat(tempArr).map((item, idx) => {
          if (this.typeObj.sheetType === 'PO' && this.title === '新增') {
            item.sheetLot = idx + 1;
          }
          return item;
        }),
        ['sheetLot'],
        ['asc']
      );
    }
  }
};
</script>

<style lang="scss" scoped>
//::v-deep .avue-form__group .avue-form__menu.avue-form__menu--center {
//  display: none;
//}
.dialog-footer {
  display: flex;
  padding-top: 20px;
  justify-content: flex-end;
}

//::v-deep .el-dialog .avue-crud__menu {
//  display: none;
//}
</style>
